package com.mes.check.manager;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mes.check.manager.iface.ICheckTaskAssignManager;
import com.mes.check.manager.iface.ICheckTaskManager;
import com.bstek.dorado.data.provider.Page;
import com.mes.basicdata.dao.iface.IDeptFunctionDao;
import com.mes.basicdata.dao.iface.IEmployeeDao;
import com.mes.basicdata.domain.Employee;
import com.mes.check.dao.CheckTaskDao;
import com.mes.check.dao.iface.ICheckBillDao;
import com.mes.check.dao.iface.ICheckTaskAssignDao;
import com.mes.check.dao.iface.ICheckTaskDao;
import com.mes.check.domain.CheckBill;
import com.mes.check.domain.CheckTask;
import com.mes.check.domain.CheckTaskAssign;
import com.mes.common.domain.BasicModel;
import com.mes.common.manager.BasicManager;
import com.mes.common.util.SysMessageUtil;
import com.mes.common.util.SysUtil;
import com.mes.task.dao.iface.IAssignmentDeviceDao;
import com.mes.task.dao.iface.IOperationTaskDao;
import com.mes.task.domain.AssignmentDevice;
import com.mes.task.domain.OperationTask;
import com.mes.task.domain.WorkRecord;
import com.mes.task.manager.iface.IOperationTaskManager;

@Component
public class CheckTaskManager extends BasicManager<CheckTask> implements ICheckTaskManager {

	public final static Log log = LogFactory.getLog(CheckTaskManager.class);

	@Autowired
	public SysUtil sysUtil;
	@Autowired
	public IDeptFunctionDao deptFunctionDao;
	@Autowired
	public ICheckTaskDao checkTaskDao;
	@Autowired
	public ICheckTaskAssignDao checkTaskAssignDao;
	@Autowired
	private ICheckBillDao checkBillDao;
	@Autowired
	public IOperationTaskDao operationTaskDao;
	@Autowired
	private IEmployeeDao employeeDao;
	@Autowired
	private ICheckTaskAssignManager checkTaskAssignManager;
	@Autowired
	private IOperationTaskManager operationTaskManager;
	@Autowired
	private IAssignmentDeviceDao assignmentDeviceDao;

	/**
	 * 将检验任务派工给检验员
	 * 
	 * @param checkTask
	 * @param checker
	 * @param assnQty
	 * @throws Exception
	 */
	@Override
	public void dispatchCheckTask(CheckTask checkTask, String checkerUid, Float assnQty) throws Exception {

		if (checkerUid == null)
			checkerUid = SysUtil.getSessionEmployeeUid();
		// TODO Auto-generated method stub
		if (checkTask.getCheckTaskState() >= CheckTask.CHECKTASKSTATE_DISPATCHED)
			return;

		float dispatchedQty = checkTaskDao.getDispatchedQty(checkTask.getUuid());
		if (assnQty == null) {
			assnQty = checkTask.getPlanQty() - dispatchedQty;
		}
		if (checkTask.getPlanQty() <= assnQty + dispatchedQty){
			checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_DISPATCHED);
//			checkTask.setCheckerUid(checkerUid);
			this.update(checkTask);
		}

		CheckTaskAssign checktaskassn = new CheckTaskAssign();
		checktaskassn.setCheckTaskUid(checkTask.getUuid());
		checktaskassn.setCheckerUid(checkerUid);
		checktaskassn.setAssnQty(assnQty == null ? checkTask.getPlanQty() : assnQty);
		checktaskassn.setAssnStart(checkTask.getPlanStart());
		checktaskassn.setAssnFinish(checkTask.getPlanFinish());
		checktaskassn.setCheckAssnState(0);
		checktaskassn.setNotes(checkTask.getNotes());
		checktaskassn.setCreatorUid(checkerUid);
		checktaskassn.setCreateTime(new Date());
		checkTaskAssignManager.add(checktaskassn);

		// 应该统一将这些消息都放在事件处理中
		// TODO 应该参数化
		if (checkTask.getCheckTaskType() != null
				&& checkTask.getCheckTaskType().equals(CheckTask.CHECKTASKTYPE_FIRSTCHECK)) {
			if (checkTask.getOperationTask() != null && checkTask.getOperationTask().getDeviceUid() != null) {
				Employee checker = this.employeeDao.getById(checkerUid);
				if (checker != null) {
					String content = "首检任务 " + "已派给 " + checker.getEmployeeName() + ","
							+ checkTask.getOperationTask().toFriendlyString();
					SysMessageUtil.sendDeviceMessage(checkTask.getOperationTask().getDeviceUid(), content, false);
				}
			}
		}
	}

	/**
	 * 取消检验任务派工
	 * 
	 * @param checkTaskAssign
	 * @throws Exception
	 */
	public void cancelDispatchCheckTask(CheckTaskAssign assn) throws Exception {
		if(assn.getCheckAssnState() == CheckTaskAssign.CHECKASSNSTATE_CREATED){
			checkTaskAssignDao.delete(assn);
			CheckTask checkTask = assn.getCheckTask();
			float receivedQty = checkTaskDao.getReceivedQty(checkTask);
			if(receivedQty > 0) {
				checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_READY);
			} else {
				checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_NOTREADY);
			}
			checkTaskDao.update(checkTask);
		}else{
			throw new Exception("该检验派工状态不允许取消");
		}
	}

	/**
	 * 开始检验任务
	 * 
	 * @param checkTaskUid
	 * @throws Exception
	 */
	@Override
	public void startCheckTask(String checkTaskUid) throws Exception {
		CheckTask checkTask = (CheckTask) this.checkTaskDao.getById(checkTaskUid);
		if (checkTask != null)
			this.startCheckTask(checkTask);
	}
	
	/**
	 * 开始检验任务
	 * 
	 * @param checkTask
	 * @throws Exception
	 */
	@Override
	public void startCheckTask(CheckTask checkTask) throws Exception {
		if (checkTask.getCheckTaskState() >= CheckTask.CHECKTASKSTATE_STARTED) {
			return;
		}
		checkTask.setActualStart(new Date());
		checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_STARTED);
		if (checkTask.getChecker() == null)
			checkTask.setCheckerUid(SysUtil.getSessionEmployeeUid());
		try {
			this.update(checkTask);
		} catch (Exception e) {
			e.printStackTrace();
		}

//		// 应该统一将这些消息都放在事件处理中
//		// lqm,应该参数化
//		if (checkTask.getCheckTaskType().equals(CheckTask.FIRSTCHECK_THIRD_TASK)) {
//			if (checkTask.getOperationTask() != null && checkTask.getOperationTask().getDeviceUid() != null) {
//
//				String content = "检验已开始 " + checkTask.getOperationTask().toFriendlyString();
//				MMUtils.sendDeviceMessage(checkTask.getOperationTask().getDeviceUid(), content, true);
//			}
//		}

	}
	
	/**
	 * 完成检验任务
	 * 
	 * @param checkTaskUid
	 * @throws Exception
	 */
	@Override
	public void completeCheckTask(String checkTaskUid) throws Exception {
		CheckTask checkTask = (CheckTask) this.checkTaskDao.getById(checkTaskUid);
		if (checkTask != null)
			this.completeCheckTask(checkTask);
	}

	/**
	 * 完成检验任务
	 * 
	 * @param checkTaskUid
	 * @throws Exception
	 */
	@Override
	public void completeCheckTask(CheckTask checkTask) throws Exception {
		if (checkTask.getCheckTaskState() >= CheckTask.CHECKTASKSTATE_COMPLETED) {
			return;
		}
		checkTask.setActualFinish(new Date());
		checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_COMPLETED);
		try {
			this.update(checkTask);
		} catch (Exception e) {
			e.printStackTrace();
		}

//		// 应该统一将这些消息都放在事件处理中
//		// lqm,应该参数化
//		if (checkTask.getOperationTask() != null && checkTask.getOperationTask().getDeviceUid() != null) {
//			String content = "*" + "检测完成。";
//			if (checkTask.getCheckWorkCenter() != null)
//				content += "设备：" + checkTask.getCheckWorkCenter().getWorkCenterName() + "，";
//
//			content += " 任务：" + checkTask.getOperationTask().toFriendlyString();
//			content += checkTask.getOperationTask().toFriendlyString();
//
//			List<CheckBill> checkList = this.checkBillDao.getCheckBillsByCheckTaskUid(checkTask.getUuid());
//
//			if (checkList != null && checkList.size() > 0) {
//				String result = checkList.get(0).getDefectQty() == null || checkList.get(0).getDefectQty().equals(0d)
//						? "合格" : "不合格";
//				content += "结论为:" + result + "，" + checkTask.getOperationTask().toFriendlyString();
//
//			}
//			MMUtils.sendDeviceMessage(checkTask.getOperationTask().getDeviceUid(), content, true);
//		}
	}
	
	/**
	 * 完成检验任务
	 * 
	 * @param checkTaskUid
	 * @throws Exception
	 */
	@Override
	public void feedbackCheckTask(String checkTaskAssignUid) throws Exception {
		CheckTaskAssign checkTaskAssign = (CheckTaskAssign) this.checkTaskAssignDao.getById(checkTaskAssignUid);
		if (checkTaskAssign != null)
			this.feedbackCheckTask(checkTaskAssign);
	}
	
	/**
	 * 通过checkTaskAssign反馈检验任务
	 * 
	 * @param checkTaskUid
	 * @throws Exception
	 */
	@Override
	public void feedbackCheckTask(CheckTaskAssign checkTaskAssign) throws Exception {
		CheckTask checkTask = checkTaskAssign.getCheckTask();
		
		if (checkTask.getCheckTaskState() >= CheckTask.CHECKTASKSTATE_COMPLETED) {
			return;
		}else{
			checkTaskAssign.setCompleteQty(checkTaskAssign.getAssnQty());
			float completeQty = checkTask.getCompleteQty();
			completeQty = completeQty + checkTaskAssign.getCompleteQty();
			checkTask.setCompleteQty(completeQty);
			
			if(checkTask.getCompleteQty() >= checkTask.getSendQty()){
				checkTask.setActualFinish(new Date());
				checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_COMPLETED);
				
				// 如果检验任务完成了，那么将该任务下的所有检验单设置为关闭（结案）状态
				List<CheckBill> checkBills = checkBillDao.getCheckBillsByCheckTaskUid(checkTask.getUuid());
				for(CheckBill checkBill : checkBills){
					checkBill.setCheckBillState(CheckBill.CHECK_BILLSTATE_CLOSED);
					checkBillDao.update(checkBill);
				}
			}
			this.update(checkTask);
			
			// 对于有对应专检工序的检验任务处理
			if(checkTask.getCheckTaskType() == CheckTask.CHECKTASKTYPE_SUMMARYCHECK || 
					checkTask.getCheckTaskType() == CheckTask.CHECKTASKTYPE_REWORKCHECK){
				
				OperationTask operationTask = checkTask.getOperationTask();
				if(operationTask.getTaskState() < OperationTask.TASKSTATE_COMPLETED){
					
					WorkRecord workRecord = new WorkRecord();
					workRecord.setObjectState(BasicModel.OBJECTSTATE_TOBEADDED);
					workRecord.setTaskUid(checkTask.getTaskUid());
					workRecord.setWorkDate(new Date());
					workRecord.setWorkerUid(SysUtil.getSessionEmployeeUid());
					float restQty = checkTask.getPlanQty() - checkTask.getCompleteQty();
					if(restQty <= checkTaskAssign.getCompleteQty()){
						workRecord.setCompleteQty(restQty);
					}else{
						workRecord.setCompleteQty(checkTaskAssign.getCompleteQty());
					}
					List<WorkRecord> workRecords = new ArrayList<WorkRecord>();
					workRecords.add(workRecord);
					operationTaskManager.feedbackTask(workRecords);
				}
			}
		}
	}
	
	
	
	
	
	
	
	
	/**以下方法暂时没有使用到，使用到再移上来******************/
	
	
	@Override
	public void passCheckTask(List<CheckTask> checkTaskList) throws Exception {
		for (CheckTask checkTask : checkTaskList) {
			this.passCheckTask(checkTask);
		}
	}

	@Override
	public void passCheckTask(CheckTask checkTask) throws Exception {
		checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_STARTED);
		this.update(checkTask);
	}

	@Override
	public List<CheckTask> getComingCheckTasksOfCheckDept(String deptUid, Date beforeDate, Page<CheckTask> page)
			throws Exception {
		// TODO Auto-generated method stub
		List<CheckTask> checkTasks = this.checkTaskDao.getComingCheckTasksOfCheckDept(deptUid, beforeDate, page);
		// 设置计划开始时间
		if (checkTasks != null && checkTasks.size() > 0) {

			Calendar calendar = Calendar.getInstance();

			for (CheckTask checkTask : checkTasks) {
				if (checkTask.getOperationTask() == null)
					continue;
				if (checkTask.getPlanStart() == null || checkTask.getPlanStart().before(calendar.getTime())) {
					Date planStart = null;
					if (CheckTask.CHECKTASKTYPE_FIRSTCHECK.equals(checkTask.getCheckTaskType())) {

						planStart = calFirstCheckStart(checkTask);

					} else if (CheckTask.CHECKTASKTYPE_OPERATIONCHECK.equals(checkTask.getCheckTaskType())) {

						if (checkTask.getOperationTask() != null
								&& checkTask.getOperationTask().getPlanFinish() != null)
							planStart = checkTask.getOperationTask().getPlanFinish();

					} else if (CheckTask.CHECKTASKTYPE_SUMMARYCHECK.equals(checkTask.getCheckTaskType())) {
						if (checkTask.getOperationTask() != null)
							if (checkTask.getOperationTask().getPlanStart() != null)
								planStart = checkTask.getOperationTask().getPlanStart();

					}
					if (planStart == null) {

						planStart = calendar.getTime();
						// lqm todo
						// 应该允许参数配置
						// 缺省为一个班次后
						calendar.add(Calendar.HOUR, 8);
						planStart = calendar.getTime();
					}
					checkTask.setPlanStart(planStart);

				}
			}

			Collections.sort(checkTasks, new Comparator<CheckTask>() {
				public int compare(CheckTask o1, CheckTask o2) {
					int i = 0;
					int typeCompare = o1.getCheckTaskType().compareTo(o2.getCheckTaskType());
					if (typeCompare == 0) {
						return (o1.getPlanStart().compareTo(o2.getPlanStart()));

					} else
						// 如果任务2锁定
						return typeCompare;

				}
			});
		}
		return checkTasks;
	}

	@Override
	public List<CheckTask> getComingCheckTasks(String deptUid, Date beforeDate, Page page) throws Exception {
		// TODO Auto-generated method stub
		List<CheckTask> checkTasks = this.checkTaskDao.getComingCheckTasks(deptUid, beforeDate, page);
		// 设置计划开始时间
		if (checkTasks != null && checkTasks.size() > 0) {

			Calendar calendar = Calendar.getInstance();

			for (CheckTask checkTask : checkTasks) {
				if (checkTask.getPlanStart() == null || checkTask.getPlanStart().before(calendar.getTime())) {
					Date planStart = null;
					if (CheckTask.CHECKTASKTYPE_FIRSTCHECK.equals(checkTask.getCheckTaskType())) {

						planStart = calFirstCheckStart(checkTask);

					} else if (CheckTask.CHECKTASKTYPE_OPERATIONCHECK.equals(checkTask.getCheckTaskType())) {

						if (checkTask.getOperationTask() != null
								&& checkTask.getOperationTask().getPlanFinish() != null)
							planStart = checkTask.getOperationTask().getPlanFinish();

					} else if (CheckTask.CHECKTASKTYPE_SUMMARYCHECK.equals(checkTask.getCheckTaskType())) {
						if (checkTask.getOperationTask() != null && checkTask.getOperationTask().getPlanStart() != null)
							planStart = checkTask.getOperationTask().getPlanStart();

					}
					if (planStart == null) {

						planStart = calendar.getTime();
						// lqm todo
						// 应该允许参数配置
						// 缺省为一个班次后
						calendar.add(Calendar.HOUR, 8);
						planStart = calendar.getTime();
					}
					checkTask.setPlanStart(planStart);

				}
			}

			Collections.sort(checkTasks, new Comparator<CheckTask>() {
				public int compare(CheckTask o1, CheckTask o2) {
					int i = 0;
					int typeCompare = o1.getCheckTaskType().compareTo(o2.getCheckTaskType());
					if (typeCompare == 0) {
						return (o1.getPlanStart().compareTo(o2.getPlanStart()));

					} else
						// 如果任务2锁定
						return typeCompare;

				}
			});
		}
		return checkTasks;
	}

	public Date calFirstCheckStart(CheckTask checkTask) {
		OperationTask operationTask = checkTask.getOperationTask();
		// if (operationTask.getDevice() == null) {
		// log.error("计算首件检验开始时间时工序的设备信息不能为空！" + operationTask);
		// return null;
		// }

		if (operationTask == null || !(operationTask.getTaskState() == OperationTask.TASKSTATE_STARTED)) {
			log.debug("只有已开始的任务才需要计算首件检验开始时间！" + operationTask);
			return null;
		}

		Date firstCheckStart = null;
		// 如果已经完成装卡，则直接
		// ScheduleScheme scheme = operationTask.getScheme();
		Calendar calendar = Calendar.getInstance();
		Date currentTime = calendar.getTime();
		// calendar.setTime(scheme.getScheduleCurrentTime());
		Date taskStart = operationTask.getActualStart() == null ? currentTime : operationTask.getActualStart();
		// if (operationTask.getTaskState() ==
		// SOperationTask.TASKSTATE_PREPARE_COMPLETED) {
		// firstCheckStart =
		// this.scheduleDeviceManager.calFinishTime(operationTask.getDevice(),
		// taskStart, operationTask.getEstiRunTime());
		// //
		// calendar.add(Calendar.MINUTE,(int)Math.round(operationTask.getEstiRunTime()));
		// // firstCheckStart=calendar.getTime();
		// } else
		if (operationTask.getTaskState() == OperationTask.TASKSTATE_STARTED) {
			// firstCheckStart =
			// this.scheduleDeviceManager.calFinishTime(operationTask.getDevice(),
			// taskStart, operationTask.getEstiPreTime() +
			// operationTask.getEstiRunTime());
			calendar.setTime(taskStart);
			double estiPreopTime = operationTask.getEstiPreOpTime() == null ? 0 : operationTask.getEstiPreOpTime();
			double estiRunTime = operationTask.getEstiRunTime() == null ? 0 : operationTask.getEstiRunTime();
			calendar.add(Calendar.MINUTE, (int) Math.round(estiPreopTime + estiRunTime));
			firstCheckStart = calendar.getTime();
		}
		// 是否要增加一个状态位，首件加工开始
		// lqm todo

		if (firstCheckStart.before(currentTime)) {
			firstCheckStart = calendar.getTime();
			// lqm todo
			// 应该允许参数配置
			calendar.add(Calendar.HOUR, 2);
			firstCheckStart = calendar.getTime();
		}

		return firstCheckStart;
	}

	@Override
	public void createFirstCheckTask(String taskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void createFirstCheckTask1(String taskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void createFirstCheckTask2(String taskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public CheckTask createFirstCheckTask3(String taskUid) throws Exception {
		OperationTask operationTask = (OperationTask) this.operationTaskDao.getById(taskUid);
		if (operationTask == null)
			throw new Exception("根据任务唯一号找不到对应工序任务" + taskUid);

		return this.createFirstCheckTask3(operationTask);

	}

	@Override
	public CheckTask createFirstCheckTask3(OperationTask operationTask) throws Exception {
		// 不存在时产生
		CheckTask checkTask = this.getFirstCheckTask3(operationTask);
		if (checkTask == null) {

			// OperationTask.TASKTYPE_CHECK
			// 是否应该用needfirstCheck
			// 非汇检工序,且工艺里定义了需要检验
			if (operationTask.getTaskType() == null
					|| !operationTask.getTaskType().equals(OperationTask.TASKTYPE_CHECK)) {
				if (operationTask.getIsNeedCheck() != null && operationTask.getIsNeedCheck()) {
					checkTask = new CheckTask();
					checkTask.setTaskUid(operationTask.getTaskUid());
					checkTask.setCheckTaskType(CheckTask.CHECKTASKTYPE_FIRSTCHECK);
					checkTask.setPlanQty(1f);
					checkTask.setDeptUid(operationTask.getMasterShopUid());
					checkTask.setCheckDeptUid(this.deptFunctionDao.getCheckDutyDeptUid(checkTask.getDeptUid()));
					checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_DRAG);
					checkTask.setIsSuspended(false);
					checkTask.setDispatchGrade(2);// 这个需要重新设计和考虑
					this.add(checkTask);
				}
			}

		}

		return checkTask;

	}

	@Override
	public void createOperationCheckTask(String taskUid) throws Exception {

		// 不存在时产生
		if (!this.isOperationCheckTaskCreated(taskUid)) {
			OperationTask operationTask = (OperationTask) this.operationTaskDao.getById(taskUid);
			if (operationTask == null)
				throw new Exception("根据任务唯一号找不到对应工序任务" + taskUid);
			// 非汇检工序,且工艺里定义了需要检验
			if (operationTask.getTaskType() == null
					|| !operationTask.getTaskType().equals(OperationTask.TASKTYPE_CHECK)) {
				if (operationTask.getIsNeedCheck() != null && operationTask.getIsNeedCheck()) {
					CheckTask checkTask = new CheckTask();
					checkTask.setTaskUid(taskUid);
					checkTask.setCheckTaskType(CheckTask.CHECKTASKTYPE_OPERATIONCHECK);
					checkTask.setPlanQty(operationTask.getPlanQty());
					checkTask.setDeptUid(operationTask.getMasterShopUid());
					checkTask.setCheckDeptUid(this.deptFunctionDao.getCheckDutyDeptUid(checkTask.getDeptUid()));
					checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_DRAG);
					checkTask.setIsSuspended(false);
					checkTask.setDispatchGrade(2);// 这个需要重新设计和考虑
					this.add(checkTask);
				}
			}

		}

	}

	@Override
	public boolean isFirstCheckTask1Created(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean isFirstCheckTask2Created(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		return false;
	}

	private CheckTask getFirstCheckTask3(OperationTask operationTask) {
		CheckTask checkTask = null;
		try {
			checkTask = this.checkTaskDao.getFirstCheckTask3(operationTask.getTaskUid());
			if (checkTask == null && operationTask.getDeviceUid() != null && operationTask.getOperationUid() != null) {
				// 取得同一台设备上同opuid的三检任务
				checkTask = this.checkTaskDao.getDeviceFirstCheckTask3(operationTask.getDeviceUid(),
						operationTask.getOperationUid());
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error("获得三检任务时出错", e);
		}
		return checkTask;

	}

	/**
	 * 还根据设备判断了首检任务是否需要多次下发 同一图号工序不需要下发
	 */
	@Override
	public boolean isFirstCheckTask3Created(OperationTask operationTask) throws Exception {
		CheckTask checkTask = this.getFirstCheckTask3(operationTask);
		return (checkTask == null) ? false : true;
		// if (this.isFirstCheckTask3Created(operationTask.getTaskUid()))
		// return true;
		// if (operationTask.getDeviceUid() == null)
		// throw new Exception("生成首检任务时一定需要有设备编号。"
		// + operationTask.getTaskUid());
		// CheckTask checkTask = this.checkTaskDao
		// .getDeviceFirstCheckTask3(operationTask.getDeviceUid());
		//
		// if (checkTask != null)
		//
		// {
		// // checkTask.getOperationTask()保险期间，没用级联
		// OperationTask operationTask1 = (OperationTask) operationTaskDao
		// .getById(checkTask.getTaskUid());
		// if (operationTask1.getOperationUid().equals(
		// operationTask.getOperationUid()))
		// return true;
		// }

		// return false;
	}

	@Override
	public boolean isOperationCheckTaskCreated(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		CheckTask checkTask = this.checkTaskDao.getOperationCheckTask(taskUid);
		return checkTask == null ? false : true;
	}

	@Override
	public void setFCT3PlanSendByTaskUid(String taskUid, Date earlyStart) throws Exception {
		// TODO Auto-generated method stub
		if (taskUid == null || earlyStart == null)
			return;
		CheckTask checkTask = this.checkTaskDao.getFirstCheckTask3(taskUid);
		if (checkTask == null)
			return;
		// lqm todo
		// 应该设置ealystart,但是现在数据库中还没有这个字段
		// if (checkTask.getPlanSend() == null) // ||
		// checkTask.getPlanSend().before(earlyStart))
		checkTask.setPlanSend(earlyStart);
		this.update(checkTask);

	}

	@Override
	public void completeFirstCheckTask3(String checkTaskUid) throws Exception {
		// TODO Auto-generated method stub
		CheckTask checkTask = (CheckTask) this.checkTaskDao.getById(checkTaskUid);
		if (checkTask != null)
			this.completeFirstCheckTask3(checkTask);
	}

	@Override
	public void startFirstCheckTask3(String checkTaskUid) throws Exception {
		CheckTask checkTask = (CheckTask) this.checkTaskDao.getById(checkTaskUid);
		if (checkTask != null)
			this.startFirstCheckTask3(checkTask);

	}

	@Override
	public void startFirstCheckTask3(CheckTask checkTask) throws Exception {
		// TODO Auto-generated method stub
		this.startCheckTask(checkTask);

	}

	@Override
	public void completeFirstCheckTask3(CheckTask checkTask) throws Exception {

		this.completeCheckTask(checkTask);
	}

	@Override
	public void completeFCT3ByTaskUid(String taskUid) throws Exception {
		// TODO Auto-generated method stub
		CheckTask checkTask = this.checkTaskDao.getFirstCheckTask3(taskUid);
		if (checkTask != null)
			this.completeFirstCheckTask3(checkTask);
	}

	@Override
	public void receiveMaterial(String checkTaskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void refuseMaterial(String checkTaskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void sendMaterial(String checkTaskUid) throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isFirstCheckTask3Created(String taskUid) throws Exception {
		CheckTask checkTask = this.checkTaskDao.getFirstCheckTask3(taskUid);
		return checkTask == null ? false : true;
	}

	@Override
	public void receiveMaterial(String taskUid, String checkTaskType) throws Exception {
		if (checkTaskType.equals(CheckTask.CHECKTASKTYPE_FIRSTCHECK)) {
			// 如果发现不存在，则先创建首检任务
			this.createFirstCheckTask3(taskUid);
			// 效率有点低
			// 应该从create中直接获取
			CheckTask checkTask = this.checkTaskDao.getFirstCheckTask3(taskUid);
			if (checkTask != null) {
				checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_READY);
				checkTask.setActualSend(new Date());
				checkTask.setSenderUid(SysUtil.getSessionEmployeeUid());
			}
		}

	}

	@Override
	public void refuseMaterial(String taskUid, String checkTaskType) throws Exception {

	}

	@Override
	public void sendMaterial(String taskUid, String checkTaskType) throws Exception {
		// TODO Auto-generated method stub

	}

	

	

	@Override
	public void refuseMaterial(CheckTask checkTask) throws Exception {
		// if (checkTask.getCheckTaskType()
		// .equals(CheckTask.FIRSTCHECK_THIRD_TASK)) {

		// 如果检验任务已经完成了，则直接退出
		if (checkTask.getCheckTaskState().equals(CheckTask.CHECKTASKSTATE_COMPLETED))
			return;

		// 重新恢复为待收料状态
		checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_NOTREADY);
		checkTask.setActualSend(null);
		checkTask.setSenderUid(null);
		checkTask.setCheckTaskId(null);
		this.update(checkTask);
		// lqm todo
		// 应该增加日志功能，记录原因

		if (checkTask.getOperationTask() != null && checkTask.getOperationTask().getDeviceUid() != null) {

			String content = "检测任务被拒收。 " + checkTask.getOperationTask().toFriendlyString();
			SysMessageUtil.sendDeviceMessage(checkTask.getOperationTask().getDeviceUid(), content, true);
		}
		// }

	}

	@Override
	public void receiveMaterial(CheckTask checkTask) throws Exception {
		// if (checkTask.getCheckTaskType()
		// .equals(CheckTask.FIRSTCHECK_THIRD_TASK)) {

		checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_READY);
		checkTask.setActualSend(new Date());
		checkTask.setSenderUid(SysUtil.getSessionEmployeeUid());

		// 如果主制部门为空，则取当前登录人员的部门编号
		if (checkTask.getCheckDeptUid() == null)
			checkTask.setCheckDeptUid(sysUtil.getSessionDeptUid());

		this.update(checkTask);
		// if (checkTask.getOperationTask() != null
		// && checkTask.getOperationTask().getDeviceUid() != null) {
		//
		// String content = "首件已收物料 "
		// + checkTask.getOperationTask().toFriendlyString();
		// MMUtils.sendDeviceMessage(checkTask.getOperationTask()
		// .getDeviceUid(), content, false);
		// }
		// }

	}

	@Override
	public void receiveMaterial(List<CheckTask> checkTasks) throws Exception {
		for (CheckTask checkTask : checkTasks) {
			this.receiveMaterial(checkTask);
		}

	}

	@Override
	public CheckTask getUnRegisterCheckTask(String deviceUid) throws Exception {
		// TODO Auto-generated method stub

		List<AssignmentDevice> assignmentDeviceList = assignmentDeviceDao.getDeviceUnFinishedAssignments(deviceUid,
				null);
		if (assignmentDeviceList != null && assignmentDeviceList.size() > 0) {
			for (AssignmentDevice assignmentDevice : assignmentDeviceList) {
				CheckTask checkTask = this.checkTaskDao.getFirstCheckTask3(assignmentDevice.getTaskUid());
				if (checkTask != null && checkTask.getCheckTaskState() < CheckTask.CHECKTASKSTATE_READY)
					return checkTask;
			}
		}
		return null;
	}

	@Override
	public void registerFirstCheckTask(OperationTask operationTask, String checkDeptUid, String checkWorkCenterUid,
			Integer keyCount, String registerEmployeeUid) throws Exception {
		// TODO Auto-generated method stub
		CheckTask checkTask = this.checkTaskDao.getUnFinishFirstCheckTask3(operationTask.getTaskUid(), checkDeptUid);
		if (checkTask != null) {
			if (checkTask.getCheckTaskState().equals(CheckTask.CHECKTASKSTATE_READY))
				throw new Exception("该道工序的检测任务已经登记过了，请不要重复登记！");
			else {
				this.receiveMaterial(checkTask);// 再次收料
				// checkTask.setSenderUid(registerEmployeeUid);
				// checkTask.setActualSend(new Date());
				// checkTask.setCheckTaskState(CheckTask.CHECK_TASKSTATE_READY);
				// this.update(checkTask);
			}
		} else {
			// lqmtodo
			// 应该有特性数的明细
			checkTask = new CheckTask();
			checkTask.setTaskUid(operationTask.getTaskUid());
			checkTask.setCheckTaskType(CheckTask.CHECKTASKTYPE_FIRSTCHECK);
			checkTask.setPlanQty(1f);
			checkTask.setDeptUid(operationTask.getMasterShopUid());
			checkTask.setCheckDeptUid(checkDeptUid);
			checkTask.setCheckWorkCenterUid(checkWorkCenterUid);
			checkTask.setKeyCount(keyCount);
			checkTask.setCreatorUid(registerEmployeeUid);
			checkTask.setCreateTime(new Date());
			checkTask.setSenderUid(registerEmployeeUid);
			checkTask.setActualSend(new Date());
			// lqmtodo
			// 以后应该有特性数的明细
			checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_READY);
			checkTask.setIsSuspended(false);
			checkTask.setDispatchGrade(2);// 这个需要重新设计和考虑
			this.add(checkTask);
		}

	}

	@Override
	public void registerFirstCheckTask(String operationTaskUid, String checkDeptUid, String checkWorkCenterUid,
			Integer keyCount, String registerEmployeeUid) throws Exception {
		// TODO Auto-generated method stub
		OperationTask operationTask = (OperationTask) this.operationTaskDao.getById(operationTaskUid);
		if (operationTask != null)
			this.registerFirstCheckTask(operationTask, checkDeptUid, checkWorkCenterUid, keyCount, registerEmployeeUid);

	}

	@Override
	public void feedbackCheckRec(String checkTaskUid, String checkerUid, float checkQty) throws Exception {
		// TODO Auto-generated method stub
		try {
			CheckTask checkTask = (CheckTask) this.getById(checkTaskUid);
			if (checkTask != null)

			{
				if (checkTask.getCheckTaskState() != null
						&& checkTask.getCheckTaskState().equals(CheckTask.CHECKTASKSTATE_COMPLETED)) {
					throw new RuntimeException("该项检验任务已经完成,请确认是否重复反馈！");

				}

				checkTask.setCheckerUid(checkerUid);
				if (checkTask.getCompleteQty() != null)
					checkTask.setCompleteQty(checkTask.getCompleteQty() + checkQty);
				else
					checkTask.setCompleteQty(checkQty);

				double planQty = checkTask.getOperationTask().getPlanQty();

				if (checkTask.getCompleteQty().equals(planQty)) {
					checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_COMPLETED);
					checkTask.setActualFinish(new Date());
				} else if (checkTask.getCompleteQty() > planQty) {

					throw new RuntimeException("检验任务的反馈完成数大于计划数 " + checkTask.getPlanQty() + ",请确认是否重复反馈！");

				}

			}
		} catch (RuntimeException e) {
			// TODO Auto-generated catch block
			log.error("反馈检验记录时出错，", e);
			throw e;
		}

	}

	/**
	 * 提交收件三检任务
	 * 
	 * @param operationTask
	 */
	public void submitFirstCheckTask3(String taskUid) {
		OperationTask operationTask;
		try {
			operationTask = this.operationTaskDao.getById(taskUid);
			if (operationTask != null)
				this.submitFirstCheckTask3(operationTask);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 提交收件三检任务
	 * 
	 * @param operationTask
	 */
	public void submitFirstCheckTask3(OperationTask operationTask) {
		// 找到检验主管部门
		String checkDeptUid = deptFunctionDao.getCheckDutyDeptUid(operationTask.getMasterShopUid());

		try {
			// 其中会自动判断是否存在三检任务，有则不再生成
			CheckTask checkTask = this.createFirstCheckTask3(operationTask);
			// CheckTask checkTask =
			// this.checkTaskDao.getUnFinishFirstCheckTask3(
			// operationTask.getTaskUid(), checkDeptUid);

			if (checkTask != null)
				this.receiveMaterial(checkTask);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			log.error(e);
		}

	}

	@Override
	public void registerCheckTask(OperationTask operationTask, String checkTaskType, String checkDeptUid,
			String checkWorkCenterUid, Integer keyCount, String registerEmployeeUid, Date lateFinish, Float sendQty,
			Boolean isDevicePause, String checkTaskId) throws Exception {
		// TODO Auto-generated method stub
		CheckTask checkTask = this.checkTaskDao.getUnFinishCheckTask(operationTask.getTaskUid(), checkTaskType,
				checkDeptUid, checkWorkCenterUid);
		if (checkTask != null) {
			if (checkTask.getCheckTaskState().equals(CheckTask.CHECKTASKSTATE_READY))
				throw new Exception("该道工序的检测任务已经登记过了，请不要重复登记！");
			else {
				this.receiveMaterial(checkTask);// 再次收料
				// checkTask.setSenderUid(registerEmployeeUid);
				// checkTask.setActualSend(new Date());
				// checkTask.setCheckTaskState(CheckTask.CHECK_TASKSTATE_READY);
				// this.update(checkTask);

				checkTask.setCheckTaskId(checkTaskId);
				this.update(checkTask);
			}
		} else {
			// lqmtodo
			// 应该有特性数的明细
			checkTask = new CheckTask();
			checkTask.setTaskUid(operationTask.getTaskUid());
			checkTask.setCheckTaskType(checkTaskType);
			checkTask.setPlanQty(sendQty);
			// 送检人所在部门
			Employee sender = employeeDao.getById(registerEmployeeUid);
			if (sender != null)
				checkTask.setDeptUid(sender.getDeptUid());

			checkTask.setCheckDeptUid(checkDeptUid);
			checkTask.setCheckWorkCenterUid(checkWorkCenterUid);
			checkTask.setKeyCount(keyCount);
			checkTask.setCreatorUid(registerEmployeeUid);
			checkTask.setCreateTime(new Date());
			checkTask.setSenderUid(registerEmployeeUid);
			checkTask.setActualSend(new Date());
			// lqmtodo
			// 以后应该有特性数的明细
			checkTask.setCheckTaskState(CheckTask.CHECKTASKSTATE_READY);
			checkTask.setIsSuspended(false);
			checkTask.setDispatchGrade(2);// 这个需要重新设计和考虑
			checkTask.setIsDevicePause(isDevicePause);
			checkTask.setCheckTaskId(checkTaskId);

			this.add(checkTask);
		}

	}

	@Override
	public void deleteCheckTasksByTaskUid(String taskUid) throws Exception {
		// TODO Auto-generated method stub

		List<CheckTask> checkTaskList = this.checkTaskDao.getCheckTasksByTask(taskUid);
		if (checkTaskList != null && checkTaskList.size() > 0)
			this.delete(checkTaskList);

	}

	@Override
	public void receiveMaterialByTask(String taskUid) throws Exception {
		List<CheckTask> checkTaskList = this.checkTaskDao.getUnFinishCheckTasksByTask(taskUid);
		if (checkTaskList != null && checkTaskList.size() > 0) {

			for (CheckTask checkTask : checkTaskList) {
				this.receiveMaterial(checkTask);
			}

		}

	}

	@Override
	public void refuseMaterialByTask(String taskUid) throws Exception {
		List<CheckTask> checkTaskList = this.checkTaskDao.getUnFinishCheckTasksByTask(taskUid);
		if (checkTaskList != null && checkTaskList.size() > 0) {

			for (CheckTask checkTask : checkTaskList) {
				this.refuseMaterial(checkTask);
			}

		}
	}

	/**
	 * 判断某个工序的流动检验任务是否已经完成
	 * 
	 * @param taskUid
	 * @return
	 * @throws Exception
	 */
	public boolean isOperationCheckTaskFinished(String taskUid) throws Exception {
		boolean result = true;

		try {
			List<CheckTask> list = checkTaskDao.getCheckTasksByTask(taskUid);

			for (CheckTask ct : list) {
				if (CheckTask.CHECKTASKTYPE_OPERATIONCHECK.equalsIgnoreCase(ct.getCheckTaskType())) {
					if (ct.getCheckTaskState() < CheckTask.CHECKTASKSTATE_COMPLETED) {
						return false;
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}

		return result;
	}

}
